import React from 'react';
import { message } from 'antd';
import { Upload } from './index';
import styles from './styles.less';
import { Review } from '@/components';
import { getFileType, uuid } from './utils';
import uploadFileService from '@/service/upload';
import { LoadingOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons';

type Props = {
  item: Upload;
  dataIndex: number;
  onDelete(index: number): void;
  onSuccess(url: string, index: number): void;
}

class UploadItem extends React.PureComponent<Props> {
  static defaultProps = {
    onSuccess: () => null,
  };

  private getFileName = (file: File) => {
    const fileType = getFileType(file.name);
    return `${uuid()}${fileType ? `.${fileType}` : ''}`;
  };

  async componentDidMount() {
    const { file } = this.props.item;
    if (file) await this.onUpload(file);
  }

  private onUpload = async (file: File) => {
    const fileName = this.getFileName(file);
    const { dataIndex, onSuccess } = this.props;
    try {
      const data = new FormData();
      data.append('imgfile', file);
      data.append('name', fileName);
      const url = await uploadFileService(data);
      onSuccess?.(url, dataIndex);
    } catch (e) {
      message.error('上传文件失败');
    }
  };

  render() {
    const {
      item,
      onDelete,
      dataIndex,
    } = this.props;
    const { url } = item;

    const defaultState = (
      <div className={styles.default_view}>
        <LoadingOutlined />
        <span className={styles.default_view_text}>
          上传中...
        </span>
      </div>
    );
    const successState = (
      <div className={styles.upload_review}>
        <img src={url} alt="预览图" />
        <div className={styles.modal_container}>
          <Review imgUrl={url}>
            <div className={styles.modal_item}>
              <EyeOutlined />
            </div>
          </Review>
          <div
            children={<DeleteOutlined />}
            className={styles.modal_item}
            onClick={() => onDelete(dataIndex)}
          />
        </div>
      </div>
    );
    return (
      <div className={styles.upload_item}>
        {!url ? defaultState : successState}
      </div>
    );
  }
}

export default UploadItem;
